#include <iostream>
#include <string>
#include <cstring>
#include <algorithm>

#include <nsComponentManagerUtils.h>
#include <nsISimpleEnumerator.h>
#include <nsStringAPI.h>

#include "SearchLrcInDir.h"

using namespace std;

namespace
{
	bool CompareString(const std::string &lhs, const std::string &rhs)
	{
        cout << "lhs = '" << lhs << "', rhs= '" << rhs << "'" << endl;
		if (lhs.size() != rhs.size())
		{
			return false;
		}
		
		std::string lhsDup = lhs;
		std::string rhsDup = rhs;
		for (size_t i = 0; i < lhsDup.size(); i++)
		{
			if (lhsDup[i] >= 0x61 && lhsDup[i] <= 0x7A)
			{
				lhsDup[i] = lhsDup[i] - 0x61 + 0x41;
			}
			if (rhsDup[i] >= 0x61 && rhsDup[i] <= 0x7A)
			{
				rhsDup[i] = rhsDup[i] - 0x61 + 0x41;
			}
		}

		return lhsDup == rhsDup;
	}
}

CSearchLrcInDir::CSearchLrcInDir(void)
{
}

CSearchLrcInDir::~CSearchLrcInDir(void)
{
}

std::string CSearchLrcInDir::GetLrcFile(const std::string &name)
{
	if (!m_dir)
	{
		return "";
	}


	std::string songName = name;
	songName.erase(std::remove(songName.begin(), songName.end(), ' '), songName.end());
	songName.erase(std::remove(songName.begin(), songName.end(), '-'), songName.end());
	
    nsCOMPtr<nsISimpleEnumerator> dirEntry;
    m_dir->GetDirectoryEntries(getter_AddRefs(dirEntry));

    //printf("dirEntry = 0x%.16x\n", (long)dirEntry);

    PRBool hasNext = false;
    while (NS_SUCCEEDED(dirEntry->HasMoreElements(&hasNext)) && hasNext)
	{
        nsCOMPtr<nsISupports> tmp;
        dirEntry->GetNext(getter_AddRefs(tmp));

        //printf("item = 0x%.16x\n", (long)tmp);

        nsIFile* item = (nsIFile*)tmp.get();

        PRBool isFile = false;
        item->IsFile(&isFile);
		if (!isFile)
        {
			continue;
        }

        nsCString leafName;
        item->GetNativeLeafName(leafName);

		std::string fileName = leafName.get();
//        cout << "fileName = " << fileName << endl;
		std::string::size_type pos = fileName.rfind(".lrc");
		if ( pos != std::string::npos && pos == fileName.length() - 4)
		{
			fileName.erase(pos, 4);
			fileName.erase(std::remove(fileName.begin(), fileName.end(), ' '), fileName.end());
			fileName.erase(std::remove(fileName.begin(), fileName.end(), '-'), fileName.end());

			if (CompareString(fileName, songName))
			{
				// find the lrc file
                nsCString path;
                item->GetNativePath(path);
                cout << "find lrc file = " << path.get() << endl;;
				return path.get();
			}
		}

	}
	return "";
}

void CSearchLrcInDir::SetDir(const std::string &dir)
{
//    cout << "dir = " << dir << endl;
	m_dir = do_CreateInstance(NS_LOCAL_FILE_CONTRACTID);
    m_dir->InitWithNativePath(nsCString(dir.c_str()));
//    GetLrcFile("fdsjds");
}
